package org.happy.tester.loader;

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Hello world!
 */
public class AgentLoader {

    /**
     * agent 加载器，打成jar包后，执行需要指定依赖的本地包如：
     * java -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -Djava.ext.dirs=${JAVA_HOME}/lib -jar loader-0.0.1.jar
     *
     * @param args args[0]: agent位置; example:  /Users/baijingchuan/projects/qa/javassist-mock/agent/target/agent.jar
     *             args[1]: json格式参数 example: {"appIp":"192.168.64.4","clientIp":"36.112.75.34","pointcutDOS":[{"className":"org.happy.tester.app.service.impl.UserServiceImpl","methodName":"getUser"}]}
     */
    public static void main(String[] args) {
        String[] cmd = new String[]{"sh", "-c", "jps | grep jar | awk '{print $1}'"};
        Process exec = null;
        BufferedReader reader = null;
        VirtualMachine attach = null;
        try {
            exec = Runtime.getRuntime().exec(cmd);
            reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            String pid = reader.readLine();
            attach = VirtualMachine.attach("89258");

            attach.loadAgent("/Users/baijingchuan/projects/qa/javassist-mock/agent/target/agent.jar", "{\"appIp\":\"127.0.0.1\",\"clientIp\":\"114.242.175.188\",\"pointcutDOS\":[{\"className\":\"org.happy.tester.app.service.impl.UserServiceImpl\",\"methodName\":\"getUser\"}]}");
        } catch (IOException var27) {
            var27.printStackTrace();
        } catch (AttachNotSupportedException var28) {
            var28.printStackTrace();
        } catch (AgentLoadException var29) {
            var29.printStackTrace();
        } catch (AgentInitializationException var30) {
            var30.printStackTrace();
        } finally {
            try {
                attach.detach();
            } catch (IOException var26) {
                var26.printStackTrace();
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException var25) {
                    var25.printStackTrace();
                }
            }

            exec.destroy();
        }

    }


}
